package com.qiyee.dalligent.common.execption;


import com.qiyee.dalligent.module.base.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常
 *
 * @author uzdz
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 调试日志
     */
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 自定义校验异常
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BaseResponse baseExceptionHandler(HttpServletRequest request, BaseException ex) {
        logger.error("do [{}] on [{}] failed. exMsg:{}", request.getMethod(), request.getRequestURL(),
                ex.getLocalizedMessage(),ex);
        return BaseResponse.error(ex.getMessage());
    }



    /**
     * 业务异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public BaseResponse serviceExceptionHandler(HttpServletRequest request, Exception ex) throws Exception {
        if (AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class) != null) {
            throw ex;
        }

        logger.error("do [{}] on [{}] failed. exMsg:{}", request.getMethod(), request.getRequestURL(),
                ex.getLocalizedMessage(),ex);
        ex.printStackTrace();
        if (logger.isDebugEnabled()) {
            logger.error("queryString:{}, parameterMap: {}", request.getQueryString(), request.getParameterMap(), ex);
        }

        return BaseResponse.error("");
    }

   /* @ExceptionHandler({ MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BaseResponse validateExceptionHandler(HttpServletRequest request, Exception e) throws Exception {

        BindingResult bindingResult = null;
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        } else {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }

        logger.error("do [{}] on [{}] failed. exMsg:{}", request.getMethod(), request.getRequestURL(),
                e.getLocalizedMessage(),e);
        if (logger.isDebugEnabled()) {
            logger.error("queryString:{}, parameterMap: {}", request.getQueryString(), request.getParameterMap(), e);
        }
        StringBuilder errMsg = getErrorInfo(bindingResult);
        return  RCMUtil.buildException(new ParamException(errMsg.toString()));
    }

    private StringBuilder getErrorInfo(BindingResult bindingResult) {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder errMsg = new StringBuilder();
        for (ObjectError allError : allErrors) {
            FieldError fieldError = (FieldError) allError;
            Object[] arguments = fieldError.getArguments();
            String[] codes = fieldError.getCodes();
            String defaultMessage = fieldError.getDefaultMessage();
            if (defaultMessage!=null&&arguments!=null&&codes!=null&&arguments.length>2&&codes.length>3&&"Size".equals(codes[3])){
                defaultMessage=defaultMessage.replace("$",arguments[1].toString());
            }
            logger.error(defaultMessage);
            errMsg.append( defaultMessage );
            break;
        }
        return errMsg;
    }*/
}
